package com.finace.money.ui.fragment;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.design.widget.TabLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.finace.money.R;
import com.finace.money.common.Constant;
import com.finace.money.common.util.ACache;
import com.finace.money.common.util.ChooseUtil;
import com.finace.money.common.util.StringUtil;
import com.finace.money.common.util.TabLayoutUtil;
import com.finace.money.common.util.UIUtil;
import com.finace.money.data.bean.StatusListBean;
import com.finace.money.data.bean.TickBean;
import com.finace.money.di.component.AppComponent;
import com.finace.money.interfaces.OnItemClickListener;
import com.finace.money.net.socket.PushReceiver;
import com.finace.money.presenter.MainStatusPresenter;
import com.finace.money.ui.activity.LoginActivity;
import com.finace.money.ui.activity.MyChooseActivity;
import com.finace.money.ui.activity.StatusDetalActivity;
import com.finace.money.ui.adapter.StatusListViewAdapter;
import com.finace.money.ui.widget.CustomHScrollView;

import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by zhangpeng on 2017/11/23.
 */

public class MainStatusFragment extends BaseFragment implements View.OnClickListener {
    @BindView(R.id.rl_left)
    RelativeLayout rlLeft;
    @BindView(R.id.tv_head_title)
    TextView tvHeadTitle;
    @BindView(R.id.tv_right_title)
    TextView tvRightTitle;
    @BindView(R.id.tab_status)
    TabLayout tabStatus;

    @BindView(R.id.h_scrollView)
    CustomHScrollView mScrollView;
    @BindView(R.id.list_view)
    ListView mListView;
    @BindView(R.id.content_main)
    RelativeLayout mHead;

    private StatusListViewAdapter mAdapter;
    private int leftPos;//用于记录CustomHScrollView的初始位置
    private int topPos;
    private ArrayList<StatusListBean> statusLists;
    private MainStatusPresenter mMainStatusPresenter = new MainStatusPresenter();
    private ArrayList<StatusListBean> tabLists;
    private int mPosition = 0;
    private ArrayList<String> mNames;

    @Override
    public int setLayout() {
        return R.layout.fragment_status;
    }

    @Override
    public void init() {

        initView();
        initList();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PushReceiver.ACTION_TICK);
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadcastReceiver, intentFilter);
        unregisterReceiver(broadcastReceiver);
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        rlLeft.setVisibility(View.GONE);
        tvRightTitle.setVisibility(View.VISIBLE);
        tvRightTitle.setOnClickListener(this);
        tvRightTitle.setText(R.string.choose_self);
        statusLists = mMainStatusPresenter.getList();
        mNames = mMainStatusPresenter.sortTab(statusLists);

        if (mNames.size() > 0) {
            tvHeadTitle.setText(getString(R.string.quotation_h) + mNames.get(0));
            for (String name : mNames) {
                tabStatus.addTab(tabStatus.newTab().setText(name));
            }
            TabLayoutUtil.reflex(tabStatus);

            tabStatus.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    tvHeadTitle.setText(getString(R.string.quotation_h) + tab.getText().toString());
                    mPosition = tab.getPosition();
                    initData();//刷新，重新加载数据
                    mScrollView.smoothScrollTo(leftPos, topPos);//每次刷新数据都让CustomHScrollView回到初始位置，避免错乱
                    if (mAdapter != null) {
                        mAdapter.notifyDataSetChanged();
                    }
                }

                @Override
                public void onTabUnselected(TabLayout.Tab tab) {

                }

                @Override
                public void onTabReselected(TabLayout.Tab tab) {

                }
            });
        }


    }

    private void initList() {
        mHead.setFocusable(true);
        mHead.setClickable(true);
        mHead.setOnTouchListener(new MyTouchLinstener());
        mListView.setOnTouchListener(new MyTouchLinstener());
        mAdapter = new StatusListViewAdapter(mHead);
        mListView.setAdapter(mAdapter);
        initData();
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                String login = ACache.get(UIUtil.getContext()).getAsString(Constant.login);
                if(StringUtil.isNullString(login)){
                    startActivity(new Intent(UIUtil.getContext(), LoginActivity.class));
                }else {
                    Intent intent = new Intent(UIUtil.getContext(), StatusDetalActivity.class);
                    intent.putExtra("statusData", tabLists.get(i));
                    getActivity().startActivityForResult(intent, 0);
                }

            }
        });
        mAdapter.setmOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                StatusListBean bean = tabLists.get(position);
                mMainStatusPresenter.setChoose(statusLists, bean);
                mAdapter.notifyDataSetChanged();
            }
        });
    }

    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (null != intent) {
                TickBean tickBean = (TickBean) intent.getSerializableExtra(PushReceiver.DATA);
                for (StatusListBean statusListBean : tabLists) {
                    if (statusListBean.getM_Body().getM_ProductID().equals(tickBean.getSymbol())) {
                        statusListBean.getM_Body().setTickbean(tickBean);
                        mAdapter.notifyDataSetChanged();
                        return;
                    }
                }
            }
        }
    };
    int mLastMotionX, mLastMotionY;

    class MyTouchLinstener implements View.OnTouchListener {
        @Override
        public boolean onTouch(View arg0, MotionEvent e) {

            //当在表头和listView控件上touch时，将事件分发给 ScrollView
            HorizontalScrollView headSrcrollView = (HorizontalScrollView) mHead.findViewById(R.id.h_scrollView);
            headSrcrollView.onTouchEvent(e);

            return false;
        }
    }


    private void initData() {

        tabLists = mMainStatusPresenter.getTabData(mNames, statusLists, mPosition);
        mAdapter.setmData(tabLists);
        mAdapter.notifyDataSetChanged();

    }

    /**
     * 记录CustomHScrollView的初始位置
     *
     * @param l
     * @param t
     */
    public void setPosData(int l, int t) {
        this.leftPos = l;
        this.topPos = t;
    }

    @Override
    public void setupAcitivtyComponent(AppComponent appComponent) {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_right_title:

                int chooseCount = ChooseUtil.getChooseCount();
                if (chooseCount > 0) {
                    Intent intent = new Intent(UIUtil.getContext(), MyChooseActivity.class);
                    getActivity().startActivityForResult(intent, 0);
                } else {
                    UIUtil.showToastSafe(getString(R.string.choose_null_tip));
                }
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        statusLists = mMainStatusPresenter.getList();
        initData();
    }

    public void refreash() {
        if (null != mAdapter) {
            mAdapter.notifyDataSetChanged();
        }
    }

}